package com.xjscrm.console.chat.core.impl;

import cn.hutool.core.util.IdUtil;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerForwardRecordMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.frame.recv.RForwardRecordMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.service.customer.chat.ChatTalkRecordService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author mingyang.chen create in 2024/3/12 09:41
 */
@Component
@Slf4j
public class ChatForwardRecordMsgHandler extends ChatBaseMsgHandler<RForwardRecordMsg> {

    @Autowired
    private WwDeviceService deviceService;

    @Autowired
    private SendMsgProducer sendMsgProducer;

    @Autowired
    private ChatTalkRecordService chatTalkRecordService;

    @Autowired
    private ChatTalkSessionService chatTalkSessionService;

    @Override
    public SResultMsg doHandle(RForwardRecordMsg content, ChannelHandlerContext ctx) {

        Long merId = content.getMerId();
        Long recordId = content.getRecordId();
        Long talkSessionId = content.getTalkSessionId();
        Long deviceUniqueId = content.getDeviceUniqueId();
        List<String> recvWxIds = content.getRecvWxIds();

        try {
            WwDevice byId = deviceService.getById(merId, deviceUniqueId);
            if (Objects.isNull(byId)) {
                throw new BusinessException("机器人设备未找到");
            }
            //
            ChatTalkRecord talkRecord = chatTalkRecordService.getById(merId, recordId, talkSessionId);
            if (Objects.isNull(talkRecord) || Objects.isNull(talkRecord.getMsgId())) {
                return SResultMsg.fail(content, "转发失败: 聊天记录不存在");
            }
            ChatTalkSession talkSession = chatTalkSessionService.getById(merId, talkSessionId);
            if (Objects.isNull(talkSession)) {
                return SResultMsg.fail(content, "转发失败: 会话不存在");
            }

            MicaTriggerForwardRecordMsg micaTriggerForwardRecordMsg = new MicaTriggerForwardRecordMsg();

            micaTriggerForwardRecordMsg.setMsgId(talkRecord.getRemoteMsgId());
            micaTriggerForwardRecordMsg.setConversationId(talkSession.getConversationId());
            micaTriggerForwardRecordMsg.setWxIds(recvWxIds);

            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerForwardRecordMsg, MicaTriggerType.TRIGGER_FORWARD_RECORD, item -> {
                item.setReqId(IdUtil.getSnowflakeNextId());
                item.setDeviceId(byId.getDeviceId());
                item.setDeviceType(byId.getDeviceType());
            });
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

            return SResultMsg.success(content, "消息转发中");
        } catch (Exception e) {
            log.error("消息转发失败", e);
            throw new BusinessException("消息转发失败");
        }
    }

    @Override
    public boolean checkMsg(RForwardRecordMsg baseMsg) {
        return super.checkMsg(baseMsg) || !ObjectUtils.allNotNull(baseMsg.getDeviceUniqueId(), baseMsg.getTalkSessionId(), baseMsg.getRecordId()) || ObjectUtils.isEmpty(baseMsg.getRecvWxIds());
    }

    @Override
    public Class<RForwardRecordMsg> msgClass() {
        return RForwardRecordMsg.class;
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_forward_record;
    }
}
